<?php
/**
 * Mine Block
 * Mine class
 *
 * @author	Emre Hasegeli <hasegeli@itu.edu.tr>
 * @license	New BSD License
 */

namespace MineBlock;

class BlockArrayArray implements \IteratorAggregate
{
	private $blockArrayArray;

	private function setBlockArrayArrayUnderBlock()
	{
		foreach($this->blockArrayArray as $arrayId => $blockArray)
			foreach($blockArray as $id => $block) //Searching blocks vertical to horizontal order.
				if($arrayId)
					$block->SetUnderBlock($this->blockArrayArray[$arrayId - 1][$id]);

		return true;
	}

	private function setBlockArrayArrayShowedBlock()
	{
		foreach($this->blockArrayArray[0] as $id => $block)
			foreach($this->blockArrayArray as $arrayId => $blockArray) //Searching blocks horizontal to vertical order.
				if($id) //If not in the first row
				{
					if($arrayId) //If block is not on top.
						$blockArray[$id]->SetShowedBlock('up',
								$this->blockArrayArray[$arrayId - 1][$id - 1]); //Block showed up left.

					if($this->blockArrayArray[$arrayId][$id - 1]->GetTotalCost() >= $blockArray[$id]->GetShowedBlockCost())
						$blockArray[$id]->SetShowedBlock('left',
								$this->blockArrayArray[$arrayId][$id - 1]); //Block showed left.

					if(isset($this->blockArrayArray[$arrayId + 1][$id - 1])) //If there is a a block on down left.
						if($this->blockArrayArray[$arrayId + 1][$id - 1]->GetTotalCost() >= $blockArray[$id]->GetShowedBlockCost())
							$blockArray[$id]->SetShowedBlock('down',
									$this->blockArrayArray[$arrayId + 1][$id - 1]); //Block showed down left.
				}

		return true;
	}

	public function __construct($blockArrayArray)
	{
		$this->blockArrayArray = $blockArrayArray;

		$this->setBlockArrayArrayUnderBlock();
		$this->setBlockArrayArrayShowedBlock();
	}

	public function getIterator()
	{
		return new \ArrayIterator($this->blockArrayArray);
	}

	public static function GetFromCSV($cSVFilePath)
	{
		$file = fopen($cSVFilePath, 'r');

		$costArrayId = 0;
		while($costArrayArray[$costArrayId++] = fgetcsv($file));

		require_once __DIR__.'/Block.class.php';

		foreach($costArrayArray as $costArrayId => $costArray)
			if(is_array($costArray))
				foreach($costArray as $costId => $cost)
					$blockArrayArray[$costArrayId][$costId] = new Block($cost);

		return new self($blockArrayArray);
	}

	private $maximumTotalCostTopBlock;

	public function GetMaximumTotalCostTopBlock()
	{
		if(empty($this->maximumTotalCostTopBlock))
			foreach($this->blockArrayArray[0] as $block) //Searching the blocks on top.
				if((empty($this->maximumTotalCostTopBlock)) or ($this->maximumTotalCostTopBlock->GetTotalCost() <= $block->GetTotalCost()))
					$this->maximumTotalCostTopBlock = $block;

		return $this->maximumTotalCostTopBlock;
	}
}
